<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>websocket_test</title>
</head>
<body>
    <h1>聊天室</h1>
    <input type="text" name="" id="sendTxt">
    <button id="sendBtn">发送</button>
     <script>
         function showMessage(data){
            var div = document.createElement('div');
            div.innerHTML = data;
            document.body.appendChild(div)
         }
        var websocket =  new WebSocket("ws://localhost:3000/")
        console.log(websocket)
        websocket.onopen = function(){
            console.log("打开")
            document.getElementById("sendBtn").onclick = function(e){
                var txt = document.getElementById("sendTxt").value;
                alert()
                if(txt == ""){
                    alert("不能空")
                    return
                }
                websocket.send(txt)
             }
        }
        websocket.onclose = function(){
            console.log("guanbi")
            document.getElementById("recv").innerHTML = "   "
        }
        websocket.onmessage = function(e){
            console.log(e);
            console.log(e.data)
            showMessage(e.data)}
    
    </script>
</body>
</html>